import React, { Component } from "react";
// import CopyToClipboard from "react-copy-to-clipboard";
import { Tabs, Button, Modal, Input, message, Form, Checkbox } from "antd";
import Articles from "../Article/Articles";
import ArticlesMon from "../Article/ArticlesMon";
import { connect } from "dva";
import DataStatistics from "../DataStatistics/DataStatistics";
import { removeCityContent, PushDraftList, PushDraft } from "../../services/services";

import { judgeMonCode } from '@/utils/formatMonTextStyle.js'

const { Search, TextArea } = Input;

const { TabPane } = Tabs;
@connect(({ add }) => ({ add: add }))
@Form.create()
class AllContentTab extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showSiteVisible: false, //显示推稿站点变量
      showPushExplainVisible: false, //显示推稿说明变量
      deleteExplainVisible: false, //删除对话框变量
      singleDeleteNote: "", //单一删除的说明
      currentIndex: -1, //当前站点的索引,
      siteList: [], //选取的要推送的列表
      selectedSiteList: [], //选取的要推送的列表
      pushNote: "" //推送说明
    };
  }
  // 显示站点选择对话框
  showSiteModule = row => {
    this.getSiteList();
    this.setState({
      showSiteVisible: true,
      currentRow: row
    });
  };
  // 获取推送站点列表
  getSiteList = () => {
    const params = {
      site_id: this.props.site_id
    };
    PushDraftList(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            siteList: res.data
          });
        } else if (res.code === 500) {
          message.error();
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 点击站点选择对话框取消
  handleSiteCancle = () => {
    this.setState({
      showSiteVisible: false
    });
  };
  // 点击站点选择对话框下一步
  nextStepChange = () => {
    this.setState({
      showSiteVisible: false,
      showPushExplainVisible: true
    });
  };
  // 选择推稿说明对话框上一步
  prepStepChange = () => {
    this.setState({
      showSiteVisible: true,
      showPushExplainVisible: false
    });
  };
  // 点击推稿说明对话框确定
  handlePushExplainOk = () => {
    this.handlePushDraft();
    this.setState({
      showPushExplainVisible: false
    });
  };
  // 推送稿件
  handlePushDraft = () => {
    this.props.form.validateFields(["pushNote"], (err, values) => {
      if (!err) {
        let receiveSite = [];
        this.state.selectedSiteList.forEach(item => {
          receiveSite.push(item.site_id);
        });
        const params = {
          site_id: this.props.site_id,
          content_type: this.props.categoryId,
          content_id: this.props.contentData.id,
          receive_site: receiveSite,
          push_notes: values.pushNote
        };
        PushDraft(params)
          .then(res => {
            if (res.code === 200) {
              message.success(res.msg);
            } else if (res.code === 500) {
              message.error(res.msg);
            } else {
              message.error("连接失败");
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    });
  };
  // 选取当前站点
  setCurrentSite = row => {
    const { selectedSiteList } = this.state;
    let nextSelectedsiteList = selectedSiteList.some(item => {
      return item.site_id === row.site_id;
    })
      ? [...selectedSiteList]
      : [...selectedSiteList, row];
    this.setState({
      selectedSiteList: nextSelectedsiteList
    });
  };
  // 选取所有站点
  setAllSite = e => {
    if (e.target.checked) {
      this.setState({
        selectedSiteList: this.state.siteList
      });
    } else {
      this.setState({
        selectedSiteList: []
      });
    }
  };
  // 获取选取站点的索引
  setCurrentIndex = event => {
    this.setState({
      currentIndex: parseInt(event.currentTarget.getAttribute("index"), 10)
    });
  };
  // 显示删稿说明对话框
  showdeleteExplainModel = record => {
    let articleId = [];
    articleId.push(record.id);
    this.setState({
      deleteExplainVisible: true,
      article_ids: articleId
    });
  };
  // 点击删稿说明对话框确定
  deleteExplainModalOk = () => {
    this.props.form.validateFields(["singleDeleteNote"], (err, values) => {
      if (!err) {
        const params = {
          site_id: this.props.site_id,
          content_type: this.props.categoryId,
          content_id: [this.props.contentData.id],
          notes: values.singleDeleteNote
        };
        this.deleteTableContent(params);
        this.props.parentBack();
        this.props.form.setFieldsValue({ singleDeleteNote: "" });
      }
    });
  };
  // 点击删稿说明对话框取消
  deleteExplainModalCancle = () => {
    this.props.form.resetFields();
    this.setState({
      deleteExplainVisible: false
    });
  };
  // 删除表格数据
  deleteTableContent = params => {
    removeCityContent(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            tableLoading: true,
            deleteExplainVisible: false
          });
          message.success(res.msg);
        } else if (res.code === 500) {
          message.error(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 站点搜索
  searchSite = value => {
    if (value.trim() === "") {
      this.getSiteList();
    } else {
      let arr = this.state.siteList.filter(item => {
        if (item.site_name.indexOf(value) > -1) {
          return item;
        }
      });
      this.setState({
        siteList: arr
      });
    }
  };
  goBack = () => {
    this.props.parentBack();
  };
  copyUrl = text => {
    message.success("复制成功，如果失败，请在地址栏内手动复制.");
  };
  render() {
    const { selectedSiteList, siteList } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Tabs
          defaultActiveKey={this.props.tabKey}
          onChange={() => {}}
          tabBarExtraContent={
            <div>
              <Button onClick={this.goBack}>返回上一级</Button>
            </div>
          }
        >
          <TabPane tab="文章内容" key="1">
            <div style={{ paddingLeft: 15, paddingTop: 5 }}>
              {this.props.add.rightList.indexOf("/supervise/button/push") > -1 ? (
                <Button type="primary" style={{ marginRight: 10 }} onClick={this.showSiteModule}>
                  一键推稿
                </Button>
              ) : null}
              {this.props.add.rightList.indexOf("/supervise/button/delete") > -1 ? (
                <Button type="danger" style={{ marginRight: 10 }} onClick={this.showdeleteExplainModel}>
                  一键删稿
                </Button>
              ) : null}
              {/* <CopyToClipboard text={window.location.href} onCopy={this.copyUrl}>
                <Button>复制本文链接</Button>
              </CopyToClipboard> */}
            </div>

            {/* 显示 详情内容 */}
            {judgeMonCode(this.props.contentData.title) ?
              <ArticlesMon handleGoBack={this.goBack} detailsContent={this.props} />
            :
              <Articles handleGoBack={this.goBack} detailsContent={this.props} />
            }
            {/* <Articles handleGoBack={this.goBack} detailsContent={this.props} /> */}
            
          </TabPane>
          <TabPane tab="数据统计" key="2">
            <DataStatistics statisticalData={this.props.statisticalData} />
          </TabPane>
        </Tabs>
        <Modal
          title={"选择站点"}
          width="600px"
          bodyStyle={{ height: 400, overflow: "hidden", display: "flex", backgroundColor: "#eaeaea" }}
          visible={this.state.showSiteVisible}
          onCancel={this.handleSiteCancle}
          okText="下一步"
          cancelText="取消"
          onOk={this.nextStepChange}
        >
          <div className="site-model-left">
            <Search placeholder="搜索站点名称" onSearch={this.searchSite} style={{ width: 280 }} />
            {siteList.length ? (
              <div style={{ padding: 5 }}>
                <Checkbox onChange={this.setAllSite}>全选</Checkbox>
              </div>
            ) : null}
            <ul className="site-model-left-container">
              {siteList.length &&
                siteList.map((item, i) => {
                  return (
                    <li index={i} onClick={this.setCurrentIndex} className={this.state.currentIndex === i ? "active" : ""} key={item.site_id}>
                      {item.site_name}
                      {this.state.currentIndex === i ? (
                        <span key={item.site_id} className="text" onClick={this.setCurrentSite.bind(this, item)}>
                          选取
                        </span>
                      ) : null}
                    </li>
                  );
                })}
            </ul>
          </div>
          <div className="site-model-right">
            <h5 className="site-model-right-container-title">已选择{selectedSiteList.length}个站点</h5>
            <div className="site-model-right-container">
              {selectedSiteList.map(item => {
                return <p key={item.site_id}>{item.site_name}</p>;
              })}
            </div>
          </div>
        </Modal>
        <Modal title="推送说明" visible={this.state.showPushExplainVisible} onCancel={this.prepStepChange} okText="提交" cancelText="上一步" onOk={this.handlePushExplainOk}>
          <Form onSubmit={this.handleSubmit}>
            <Form.Item>
              {getFieldDecorator("pushNote", {
                rules: [
                  { required: true, message: "请输入推送说明!" },
                  { whitespace: true, message: "不能输入空字符!" },
                  { max: 300, message: "不能大于300个字符" }
                ]
              })(<TextArea placeholder="请输入300字以内的说明。。。" allowClear rows={6} />)}
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="删稿说明" visible={this.state.deleteExplainVisible} okText="确定" cancelText="取消" onOk={this.deleteExplainModalOk} onCancel={this.deleteExplainModalCancle}>
          <Form onSubmit={this.handleSubmit} className="login-form">
            <Form.Item>
              {getFieldDecorator("singleDeleteNote", {
                rules: [
                  { required: true, message: "请输入推稿说明!" },
                  { whitespace: true, message: "不能输入空字符!" },
                  { max: 60, message: "不能大于60个字符" }
                ]
              })(<TextArea placeholder="请输入60字以内的说明。。。" allowClear rows={6} />)}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default AllContentTab;
